<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\WebPage;
use StudyBuddy\Template\Urhere;

/**
 * Controller for creating a page
 * with the "Edit" form
 * to edit question or answer
 * It creates the form object
 * and adds form to the page template
 *
 */
class Edit extends WebPage
{
	/**
	 * Name of collection that this resource
	 * belongs to. This is either QUESTIONS or ANSWERS
	 *
	 * @var string
	 */
	protected $collection;

	
	/**
	 * Resource being edited - either Question or Answer object
	 * 
	 * @var object 
	 */
	protected $oResource;

	
	/**
	 * Form object
	 * 
	 * @var object
	 */
	protected $oForm;

	protected function main(){

		$this->getResource()
		->configureEditor()
		->checkPermission()
		->makeForm()
		->setForm()
		->makeTopTabs()
		->makeRecentTags()
		->makeTutorListing()
		->setMemo();
	}


	/**
	 * @todo translate string
	 *
	 * @return object $this
	 */
	protected function setMemo(){
		$memo = '<strong>How to Edit:</strong>
		<ul>
		<li>Fix grammatical or spelling errors</li>
		<li>Clarify meaning without changing it</li>
		<li>Add related resources or links</li>
		</ul>';

		$this->aPageVars['qheader'] = '<div class="memo">'.$memo.'</div>';

		return $this;
	}
	
	protected function makeTopTabs(){
            $guest = null;
            if($this->oRegistry->Viewer->isGuest()) {
                $guest['link_ask'] = '#'; // 13
                $guest['link_ask_click'] = ' onclick="oSL.getQuickRegForm()"'; //14
            }
		$tabs = Urhere::factory($this->oRegistry)->get('tplToptabs', "questions", $guest);
		
		$this->aPageVars['topTabs'] = $tabs;

		return $this;
	}

	//hoangto tutor listing
	protected function makeTutorListing(){

		$s = $this->getSortedTutors();
		$tutors = \tplTutorBox::parse(array('tutors' => $s, 'title' => $this->_('Tutor Listing')));
		d('cp');
		$this->aPageVars['tutors'] = $tutors;

		return $this;
	}
	
	//hoangto tutor listing loop
	protected function getSortedTutors() {
		
		$cur = $this->oRegistry->Mongo->USERS->find(array('tmp_role' => 'tutor'))->sort(array('experience' => -1))->limit(9);

		$canTeach = '';
		
		$func = function(&$a) use($canTeach){
			$a['canTeach'] = $canTeach;
		};
		
		$tutors = \tplTutorListing::loop($cur, true, $func);
		
		return $tutors;
	}
	
	protected function makeRecentTags(){

		$aUserTags = $this->oRegistry->Viewer['a_f_t'];
		if(!empty($aUserTags)){
			$s = $this->getSortedRecentTags($aUserTags);
		} else {
			$s = $this->oRegistry->Cache->get('qrecent');
		}

		$tags = \tplBoxrecent::parse(array('tags' => $s, 'title' => $this->_('Recent Tags')));
		d('cp');
		$this->aPageVars['tags'] = $tags;

		return $this;
	}
	
	protected function getSortedRecentTags(array $aUserTags, $type = 'recent'){

		$limit = 9;
		if('unanswered' === $type){
			$cur = $this->oRegistry->Mongo->UNANSWERED_TAGS->find(array(), array('tag', 'i_count'))->sort(array('i_ts' => -1))->limit($limit);
		} else {
			$cur = $this->oRegistry->Mongo->QUESTION_TAGS->find(array('i_count' => array('$gt' => 0)), array('tag', 'i_count'))->sort(array('i_ts' => -1))->limit($limit);
		}

		d('got '.$cur->count(true).' tag results');
		$aTags = iterator_to_array($cur);

		d('aTags: '.print_r($aTags, 1));

		if(!empty($aTags)){
			usort($aTags, function($a, $b) use ($aUserTags){
				return (in_array($a['tag'], $aUserTags)) ? -1 : 1;
			});
		};

		d('$aTags now: '.print_r($aTags, 1));
		$html = ('unanswered' === $type) ? \tplUnanstags::loop($aTags) : \tplLinktag::loop($aTags);

		d('html recent tags: '.$html);

		return '<div class="tag"><ul>'.$html.'</ul></div>';
	}

	protected function makeForm(){
		d('cp');
		$this->oForm = new \StudyBuddy\Forms\Edit($this->oRegistry);
		$body = $this->oResource['b'];
		
		/**
		 * <pre rel="codepreview" class="xml"> 
		 */
		d('body: '.$body);
		$body = str_replace('rel="code"', 'alt="codepreview"', $body);
		$this->oForm->qbody = $body;
		$this->oForm->id = $this->oResource['_id'];
		$this->oForm->rtype = $this->oRequest['rtype'];

		if('ANSWERS' === $this->collection){
			$this->oForm->hidden = ' hidden';
		} else {
			$this->oForm->level = $this->buildSec();
			$this->oForm->subject = $this->buildSubject();
			$this->oForm->chapter = $this->buildChapter();
			//$this->oForm->dif = $this->buildDif();
			
			if($this->oRegistry->Viewer->isAdmin()) {
				//$this->setVar('dif', $this->buildDif());
				$this->oForm->dif = $this->buildDif();
			} else {
				$current = isset($this->oResource['dif']) ? $this->oResource['dif'] : '';
				$this->oForm->dif =  '<input type="hidden" value="'.$current.'" name="dif" />';
			}
                        
			$this->oForm->title = $this->oResource['title'];
			$this->oForm->id_title = $this->oResource['id_title'];
			$minTitle = $this->oRegistry->Ini->MIN_TITLE_CHARS;
			$this->oForm->addValidator('title', function($val) use ($minTitle){

				if(mb_strlen($val) < $minTitle){
					$err = 'Title must contain at least %s letters';
					return sprintf($err, $minTitle);
				}

				return true;
			});
		}

		return $this;
	}


	/**
	 * Add html of the form
	 * to page body
	 *
	 * @return object $this
	 */
	protected function setForm(){
		$form = $this->oForm->getForm();
		$this->aPageVars['body'] = $form;

		return $this;
	}


	/**
	 * Create object of type Question or Answer
	 *
	 * @return object $this
	 */
	protected function getResource(){
		$this->collection = ('q' == $this->oRequest['rtype']) ? 'QUESTIONS' : 'ANSWERS';
		$this->permission = ('QUESTIONS' === $this->collection) ? 'edit_question' : 'edit_answer';

		d('type: '.$this->collection);
		$coll = $this->oRegistry->Mongo->getCollection($this->collection);
		$a = $coll->findOne(array('_id' => (int)$this->oRequest['rid']));
		d('a: '.print_r($a, 1));

		if(empty($a)){

			throw new \StudyBuddy\Exception('Item not found');
		}

		$class = ('QUESTIONS' === $this->collection) ? '\\StudyBuddy\\Question' : '\\StudyBuddy\\Answer';

		$this->oResource = new $class($this->oRegistry, $a);

		return $this;
	}


	/**
	 * Edits can be done by owner of resource
	 * OR by someone who has necessary permission
	 *
	 * @return object $this
	 * @throws checkAccessPermission() will throw exception
	 * if Viewer does not have required permission
	 */
	protected function checkPermission(){
		if(!\StudyBuddy\isOwner($this->oRegistry->Viewer, $this->oResource)){
			if(\StudyBuddy\Points::EDIT > $this->oRegistry->Viewer->getReputation()){
				$this->checkAccessPermission();
			}
		}

		return $this;
	}
        
	protected function buildSec(){
            $s = '';
            $current = isset($this->oResource['level']) ? $this->oResource['level'] : '';
            $sec = array(
                1 => 'Sec 1',
                2 => 'Sec 2',
                3 => 'Sec 3&4'
            );

            $tpl = '<option value="%1$s"%2$s>%3$s</option>';
            foreach ($sec as $key => $val) {
                $selected = ($key == $current) ? ' selected="selected"' : '';
                $s .= vsprintf($tpl, array($key, $selected, $val));
            }

            return $s;
        }
        
	protected function buildSubject(){
            $s = '';
            $current = isset($this->oResource['subject']) ? $this->oResource['subject'] : '';
            $subject = array(
                    1 => 'E Maths',
                    2 => 'A Maths',
                    3 => 'Physics'
            );
            
            $tpl = '<option value="%1$s"%2$s>%3$s</option>';
            foreach($subject as $key => $val){
                    $selected = ($key == $current) ? ' selected="selected"' : '';
                    $s .= vsprintf($tpl, array($key, $selected, $val));
            }

            return $s;
        }
        
        protected function buildChapter(){
            $s = '';
            $current = isset($this->oResource['chapter']) ? $this->oResource['chapter'] : '';
            $s_current = isset($this->oResource['subject']) ? $this->oResource['subject'] : '';
            
            $e_maths = array(
                    1 => 'Factorisation',
                    2 => 'Numbers and four operations',
                    3 => 'Inequalities',
                    4 => 'Indices',
                    5 => 'Ratio, rate and proportion',
                    6 => 'Percentage',
                    7 => 'Speed',
                    8 => 'Algebra',
                    9 => 'Functions and graphs',
                    10 => 'Solutions of equations',
                    11 => 'Applied maths',
                    12 => 'Set language and notation',
                    13 => 'Matrices',
                    14 => 'Angles, triangles and polygons',
                    15 => 'Congruence and similarity',
                    16 => 'Properties of circles',
                    17 => 'Pythagoras\' theorem',
                    18 => 'Trigonometry',
                    19 => 'Mensuration',
                    20 => 'Coordinate geometry',
                    21 => 'Vectors',
                    22 => 'Data handling',
                    23 => 'Data analysis',
                    24 => 'Probability'
            );

            $a_maths = array(
                    1 => 'Quadratic equations and inequalities',
                    2 => 'Indices and surds',
                    3 => 'Polynomials',
                    4 => 'Simultaneous equations',
                    5 => 'Partial fractions',
                    6 => 'Binomial expansions',
                    7 => 'Exponential, logarithmic and modulus functions',
                    8 => 'Trigonometry',
                    9 => 'Coordinate geometry',
                    10 => 'Plane geometry',
                    11 => 'Differentiation',
                    12 => 'Integration'
            );

            $physics = array(
                    1 => 'Physical Quantities, Units and Measurements',
                    2 => 'Kinematics',
                    3 => 'Forces',
                    4 => 'Mass, Weight and Density',
                    5 => 'Moments',
                    6 => 'Work, Energy and Power',
                    7 => 'Pressure',
                    8 => 'Kinetic Model of Matter',
                    9 => 'Heat Capacity and Latent Heat',
                    10 => 'Transfer of Thermal Energy',
                    11 => 'Temperature',
                    12 => 'Thermal Properties of Matter',
                    13 => 'Waves',
                    14 => 'Sound',
                    15 => 'Reflection and Refraction',
                    16 => 'Lenses',
                    17 => 'Electromagnetic Spectrum',
                    18 => 'Current Electricity',
                    19 => 'Static Electricity',
                    20 => 'D.C. Circuits',
                    21 => 'Practical Electricity',
                    22 => 'Magnetism',
                    23 => 'Electromagnetism',
                    24 => 'Electromagnetic Induction',
                    25 => 'Transformers and C.R.O.'
            );
            d('cp');

            $chapter = '';
            switch ($s_current) {
                case 1:
                    $chapter = $e_maths;
                    break;
                case 2:
                    $chapter = $a_maths;
                    break;
                case 3:
                    $chapter = $physics;
                    break;
                default:
                    break;
            }

            $s = '';

            $tpl = '<option value="%1$s"%2$s>%3$s</option>';
            if($chapter != null) {
                foreach($chapter as $key => $val){
                        $selected = ($key == $current) ? ' selected="selected"' : '';
                        $s .= vsprintf($tpl, array($key, $selected, $val));
                }
            }

            return $s;
        }
        
        protected function buildDif() {
            $s = '';
            $current = isset($this->oResource['dif']) ? $this->oResource['dif'] : '';
            $dif = array(
                1 => '1',
                2 => '2',
                3 => '3',
                4 => '4',
                5 => '5'
            );

            $tpl = '<option value="%1$s"%2$s>%3$s</option>';
            foreach ($dif as $key => $val) {
                $selected = ($key == $current) ? ' selected="selected"' : '';
                $s .= vsprintf($tpl, array($key, $selected, $val));
            }
			$s = '<div class="ctl-nav-solid">
							<img alt="" src="/images/2/icon/solid.gif" />
						</div>
						<div class="ctl-nav-ct" style="position:relative">	                            
							<select name="dif" style="border:none; background:transparent; padding:0 3px 3px 0; width:86px; position:relative">
								<option value="">Difficulty</option>
								'.$s.'
							</select>
							<span style="position:absolute; float:right; bottom:0; right:0; width:24px; height:24px; background-color:#ff8e33"></span>
						</div>';
            return $s;
        }
}
